import os
import sys

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)
from utils.toml import load_mysql_config
from dao.orm import DBManager

mysql_config = load_mysql_config("./config/config.toml")

db = DBManager(
    mysql_config["host"],
    mysql_config["user"],
    mysql_config["password"],
    mysql_config["database"]
)

class LoginSchema:
    def __init__(self):
        db.connect()

    def quit(self):
        db.disconnect()
    
    # 获取学生用户数据
    def get_student(self, user_id):
        sql = 'select * from student_users where student_number = %s'
        data = db.fetchone(sql, user_id)
        return data

    # 学生注册
    def register_student(self, user_id, password):
        insert_data = db.insert(
            table="student_users",
            data={"student_number": user_id, "password": password}
        )
        return insert_data
    
    # 获取教师用户数据
    def get_teacher(self, user_id):
        sql = 'select * from teacher_users where employee_id = %s'
        data = db.fetchone(sql, user_id)
        return data
    
    # 教师注册
    def register_teacher(self, user_id, password):
        insert_data = db.insert(
            table="teacher_users",
            data={"employee_id": user_id, "password": password}
        )
        return insert_data

    # 修改教师信息
    def update_teacher(self, user_id, teacher):
        update_data = db.update(
            table="teacher_users",
            data=teacher,
            conditions={"employee_id": user_id}
        )
        return update_data
    
    # 修改学生信息
    def update_student(self, user_id, student):
        update_data = db.update(
            table="student_users",
            data=student,
            conditions={"student_number": user_id}
        )
        return update_data
    
    # 获取一个班级全部学生
    def get_class(self, class_id):
        sql = 'select * from student_users where class = %s'
        data = db.fetchall(sql, class_id)
        return data
    
    # 根据班级名称所有同学数量
    def get_class_count(self, class_name):
        print(class_name)
        sql = 'select count(*) from student_users where class_name = %s'
        data = db.fetchone(sql, class_name)
        return data if data else 0